<!--
 * @Author: hashMi 854059946@qq.com
 * @Date: 2024-01-09 09:45:09
 * @LastEditors: hashMi 854059946@qq.com
 * @LastEditTime: 2024-01-10 10:22:18
 * @FilePath: /audition-app/subPages/have-sound/sound-detail.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <view class="sound-detail container">
    <view class="sound-detail-title">{{ detailData.article_title || "" }}</view>
    <view class="sound-detail-subtitle">
      | {{ detailData.article_subtitle || "" }}
    </view>
    <view class="sound-detail-log" v-if="isShowDetailLog">
      <!-- widthFix -->
      <image :src="getDetailLog(detailData)" mode="" />
    </view>
    <view
      class="sound-detail-introduction"
      v-if="detailData.title_introduction"
    >
      <image
        class="introduction-icon"
        mode="widthFix"
        :src="
          $helper.filterCover(
            '/api/mongoFile/previewImage/jwsq/657ea7736affce1e6fd24a31'
          )
        "
      >
      </image>
      <view class="introduction-content">
        {{ detailData.title_introduction || "" }}
      </view>
    </view>

    <view class="show-title flex-a-center">
      <view class="title-icon"></view>
      <view class="title">{{ detailData.title }}</view>
    </view>
    <view class="sound-detail-show">
      <template v-if="detailData.type === '音频'">
        <sy-audio
          ref="audio"
          isCountDown
          :src="detailData.src"
          :audioTitle="`${detailData.title}--${detailData.reader}`"
          :audioCover="getImageUrl(detailData)"
          :subheading="detailData.sub_title"
          backgroundColor="#EBEBEB"
        ></sy-audio>
        <view class="person-message">
          宣讲人/{{ detailData.detail_reader }}
        </view>
      </template>
      <template v-else>
        <view class="video-container" ref="videoContainer">
          <!--  object-fit="fill" object-fit="cover" height: videoHeight + 'px'  -->
          <video
            :style="{ width: '100%', height: videoHeight + 'px' }"
            id="myVideo"
            object-fit="fill"
            :src="detailData.src"
            controls
          />
        </view>
      </template>

      <view class="audio-footer">{{ footerText }}</view>
    </view>

    <view class="sound-detail-content">
      <u-parse :content="detailData.rich_content" :tagStyle="style"></u-parse>
    </view>
    <!-- 分享按钮 -->
    <button class="share-btn" @tap="shareEvn">分享</button>

    <!-- 分享弹窗-->
    <view class="share-pro">
      <view class="share-pro-mask" v-if="deliveryFlag"></view>
      <view class="share-pro-dialog" :class="deliveryFlag ? 'open' : 'close'">
        <view class="close-btn" @tap="handleClose">
          <span class="font_family">&#xe81d;</span>
        </view>
        <view class="share-pro-title">分享</view>
        <view class="share-pro-body">
          <view class="share-item">
            <button open-type="share">
              <view class="font_family share-icon">&#xe786;</view>
              <view>分享给好友</view>
            </button>
          </view>
          <view class="share-item" @tap="handleQRcode(detailData)">
            <view class="font_family share-icon">&#xe786;</view>
            <view>生成二维码</view>
          </view>
          <view class="share-item" @tap="handleShowPoster">
            <view class="font_family share-icon">&#xe600;</view>
            <view>生成分享图片</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部分享窗口 -->
    <hch-poster
      v-if="base64ImgUrl"
      ref="hchPoster"
      @cancel="handleCancel"
      :posterData.sync="posterData"
      @previewImage="previewImage"
    />

    <!-- 模态框 -->
    <u-modal
      :show="showModal"
      width="300px"
      :zoom="false"
      @confirm="saveQrCode"
      :showCancelButton="true"
      @cancel="handleCancelBtn"
    >
      <QRCode
        v-if="uQRCode"
        ref="uqrcode"
        canvas-id="uqrcode"
        :value="uQRCode"
        size="400"
        sizeUnit="rpx"
        :loading="qrcodeLoading"
        @complete="qrCodeLoadComplete($event)"
        :options="options"
      />
    </u-modal>
  </view>
</template>

<script>
import { getModelInfo, getPublicModelInfo } from "@/api";
import { createInviteCode } from "@/api/user";
import { base64Save } from "@/common/function";
import HchPoster from "../../components/hch-poster/hch-poster.vue";
import QRCode from "@/uni_modules/Sansnn-uQRCode/components/uqrcode/uqrcode";
export default {
  components: { QRCode },
  data() {
    return {
      // 判断是否登录
      isLogin: true,
      detailData: {},
      showPopup: false,
      showModal: false,
      style: {
        p: "color: #333;font-size: 30rpx",
      },
      // 小程序码
      base64ImgUrl: "",
      // modeImage: "",
      footerText: "(点击进行播放)",
      deliveryFlag: false, //
      // 海报模板数据
      posterData: {
        //根据屏幕大小自动生成海报背景大小
        poster: {
          url: "https://kindoucloud.com:8077/api/mongoFile/previewImage/jwsq/657ac1836affce1e6fd24a11", //图片地址
          r: 10, //圆角半径
          w: 300, //海报宽度
          h: 480, //海报高度
          p: 20, //海报内边距padding
        },
        //海报主商品图
        mainImg: {
          url: "https://kindoucloud.com:8077/api/mongoFile/previewImage/jwsq/657ac1786affce1e6fd24a0c", //图片地址
          r: 10, //圆角半径
          w: 250, //宽度
          h: 200, //高度
        },
        //商品标题
        title: {
          text: "今日上新水果，牛奶草莓，颗粒饱满，每盒 200g", //文本
          fontSize: 16, //字体大小
          color: "#000", //颜色
          lineHeight: 25, //行高
          mt: 20, //margin-top
        },
        //小程序码
        codeImg: {
          url: "https://kindoucloud.com:8077/api/mongoFile/previewImage/jwsq/657ac1786affce1e6fd24a0c", //图片地址
          w: 100, //宽度
          h: 100, //高度
          mt: 20, //margin-top
          r: 50, //圆角半径
        },
        //提示信息
        tips: [
          {
            text: "社区试听小程序", //文本
            fontSize: 14, //字体大小
            color: "#2f1709", //字体颜色
            align: "center", //对齐方式
            lineHeight: 25, //行高
            mt: 20, //margin-top
          },
          {
            text: "长按/扫描识别查看资源", //文本
            fontSize: 12, //字体大小
            color: "#2f1709", //字体颜色
            align: "center", //对齐方式
            lineHeight: 25, //行高
            mt: 20, //margin-top
          },
        ],
      },
      // 视屏容器高度
      videoSize: {},
      // 父元素宽
      parentsWidth: 0,
      // 请求次数限制
      reqNumber: 0,
      videoHeight: 0,

      //  普通二维码
      uQRCode: "",
      options: {
        margin: 20,
        foregroundImageSrc: "",
        backgroundImageWidth: 20,
        backgroundImageHeight: 20,
        errorCorrectLevel: 0, //二维码容错率M
      },
      qrcodeLoading: false,
      qrcodeStatus: false,
    };
  },
  computed: {
    isShowDetailLog() {
      return this.detailData?.detail_log?.length;
    },
  },

  components: {
    HchPoster,
  },
  mounted() {},
  // #ifdef MP-WEIXIN
  onShareAppMessage() {
    return {
      title: "文明江湾，心心相映。",
    };
  },
  // #endif
  async onLoad(options) {
    const { id = "", scene = "", q = "" } = options;
    let qrId;
    if (id) {
      qrId = id;
      await this.getDetailData(getPublicModelInfo, id);
    }
    if (scene) {
      console.log(scene);
      let pathId = decodeURIComponent(scene).split('id=')[1];
      qrId = pathId;
      this.$store.commit("qrCodeLoad/incrementCounter", pathId);
      await this.getDetailData(getPublicModelInfo, pathId);
    }

    if (q) {
      let pathId = decodeURIComponent(q).split("?")[1].split("=")[1];
      qrId = pathId;
      this.$store.commit("qrCodeLoad/incrementCounter", pathId);
      await this.getDetailData(getPublicModelInfo, pathId);
    }

    uni.showLoading({ title: "二维码加载中", mask: true });
    this.uQRCode = "https://kindoucloud.com:8018/jwsp?scene=" + qrId;
  },
  onReady() {},

  methods: {
    qrCodeLoadComplete(e) {
      this.qrcodeStatus = e.success;
      if (e.success) {
        this.qrcodeLoading = false;
      } else {
        this.$message("生成失败", false);
        this.qrcodeLoading = false;
      }
      uni.hideLoading();
    },
    saveQrCode() {
      if (this.qrCodeLoading) return;
      this.$toPromise(this.$refs.uqrcode.save)
        .then(() => {
          this.$message("保存成功");
        })
        .catch(() => {
          this.$message("保存失败", false);
        });
    },

    getVideoSize(url, size = 20) {
      this.reqNumber++;
      return new Promise((resolve, reject) => {
        uni.downloadFile({
          url,
          header: {
            Range: `bytes=0-${size}000`,
          },
          success: (res) => {
            // console.log(res);
            uni.getVideoInfo({
              src: res.tempFilePath,
              success: ({ width, height }) => {
                if (!width || !height) {
                  if (this.reqNumber > 3) {
                    reject({ msg: "下载视屏失败" });
                    return;
                  }

                  resolve(this.getVideoSize(url, size + 20));
                }

                resolve({ width, height });
              },
              fail: (err) => {
                reject(err);
              },
            });
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    },

    async getDetailData(reqFn, id) {
      const { data } = await reqFn("6571251d262fbe2d9d0a826b", id);
      await this.getContainerWidth(data?.src);
      this.detailData = data;
    },

    async getContainerWidth(src) {
      const videoSize = await this.getVideoSize(src);
      const query = uni.createSelectorQuery().in(this);
      query
        .select(".video-container")
        .boundingClientRect((rect) => {
          const containerWidth = rect.width;
          this.parentsWidth = rect.width;
          this.videoHeight =
            (videoSize.height / videoSize.width) * containerWidth;
          // 强制更新组件
          this.$forceUpdate();
        })
        .exec();
    },

    // 资源log
    getImageUrl(data) {
      return this.$helper.filterCover(data?.log?.[0]?.url);
    },

    // 详情log
    getDetailLog(data) {
      return this.$helper.filterCover(data?.detail_log?.[0]?.url);
    },

    close() {
      this.showPopup = false;
    },

    // 模态框按钮
    handleConfirmBtn() {
      let that = this;
      // 向用户发起授权请求
      uni.authorize({
        scope: "scope.writePhotosAlbum",
        success: () => {
          // 已授权
          // console.log('授权成功')
          that.downLoadImg();
        },
        fail: () => {
          // 拒绝授权，获取当前设置
          uni.getSetting({
            success: (result) => {
              if (!result.authSetting["scope.writePhotosAlbum"]) {
                that.isAuth();
              }
            },
          });
        },
      });
    },

    downLoadImg() {
      wx.getImageInfo({
        src: this.base64ImgUrl,
        success: (res) => {
          wx.saveImageToPhotosAlbum({
            filePath: res.path,
            success(res) {
              wx.showToast({ title: "保存图片成功！" });
            },
            fail(err) {
              wx.showToast({ title: "保存图片失败！" });
            },
          });
        },
        fail: (err) => {
          console.log(err, "err");
        },
      });
    },

    //引导用户开启权限
    isAuth() {
      uni.showModal({
        content:
          "由于您还没有允许保存图片到您相册里,无法进行保存,请点击确定允许授权",
        success: (res) => {
          if (res.confirm) {
            uni.openSetting({
              success: (result) => {
                console.log(result.authSetting);
              },
            });
          }
        },
      });
    },

    // 获取小程序码
    async getQrCodeUrl() {
      let reqCode = await createInviteCode(this.detailData._id);
      let { data } = reqCode;
      this.modeImage = data;
      if (data.includes("base64")) {
        // base64图片
        return base64Save(data)
          .then((src) => this.$toPromise(uni.getImageInfo, { src }))
          .then(({ path }) => {
            this.base64ImgUrl = path;
            this.posterData.mainImg.url = this.$helper.filterCover(
              this.detailData.log?.[0].url
            );
            this.posterData.title.text = this.detailData.title;
            this.posterData.codeImg.url = path;
          });
      }
    },

    // 模态框取消按钮
    handleCancelBtn() {
      this.showModal = false;
    },

    // 获取小程序码codeUrl模态框二维码
    handleQRcode(data) {
      this.deliveryFlag = false;
      this.showModal = true;
      this.options.foregroundImageSrc = this.$helper.filterCover(
        data?.detail_log?.[0].url
      );
    },

    /**
     * @description: 分享弹窗
     * @param {type}
     * @return {type}
     * @author: hch
     */
    async shareEvn() {
      this.deliveryFlag = true;
    },

    /**
     * @description: 生成海报
     * @param {type}
     * @return {type}
     * @author: hch
     */
    async handleShowPoster() {
      if (this.base64ImgUrl) return;
      try {
        uni.showLoading({ title: "小程序码加载中", mask: true });
        await this.getQrCodeUrl();
        uni.hideLoading();
        this.$nextTick(() => {
          this.$refs.hchPoster.posterShow();
          this.deliveryFlag = false;
        });
      } catch (error) {
        console.error(error);
        this.$message("小程序码生成失败", false);
      }
    },

    /**
     * @description: 关闭分享弹窗
     * @param {type}
     * @return {type}
     * @author: hch
     */
    handleClose() {
      this.deliveryFlag = false;
    },

    /**
     * @description: 取消海报
     * @param {type}
     * @return {type}
     * @author: hch
     */
    handleCancel(val) {
      // this.canvasFlag = val;
    },
  },
};
</script>

<style lang="scss" scoped>
.sound-detail {
  background: #fff;
  padding: 20rpx;

  /* 按钮去掉边框 */
  button::after {
    border: none;
  }

  button {
    height: auto; //支付宝需要加
    padding-right: 0;
    padding-left: 0;
    margin-right: 0;
    margin-left: 0;
    font-size: 28rpx;
    line-height: 1;
    color: #1c1c1c;
    background: none;
    border: none; //支付宝需要加
  }

  .button-hover {
    color: #1c1c1c;
    background: none;
  }

  .poster-img {
    width: 40%;
  }

  /* 每个页面公共css */
  .content {
    height: 100%;
    text-align: center;
  }

  .share-btn {
    padding: 30rpx 60rpx;
    color: $uni-text-color-inverse;
    background-color: $u-theme-color;
  }

  .share-pro {
    z-index: 5;
    display: flex;
    line-height: 1;
    box-sizing: border-box;
    align-items: center;
    justify-content: flex-end;
    flex-direction: column;

    .share-pro-mask {
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
    }

    .share-pro-dialog {
      position: relative;
      position: fixed;
      bottom: 0;
      width: 750rpx;
      height: 310rpx;
      overflow: hidden;
      background-color: #fff;
      border-radius: 24rpx 24rpx 0 0;
      box-sizing: border-box;

      .close-btn {
        position: absolute;
        top: 0rpx;
        right: 29rpx;
        padding: 20rpx 15rpx;
      }

      .share-pro-title {
        padding: 28rpx 41rpx;
        font-size: 28rpx;
        color: #1c1c1c;
        background-color: #f7f7f7;
      }

      .share-pro-body {
        display: flex;
        font-size: 28rpx;
        color: #1c1c1c;
        flex-direction: row;
        justify-content: space-around;

        .share-item {
          display: flex;
          flex-direction: column;
          justify-content: center;
          justify-content: space-around;

          .share-icon {
            margin-top: 39rpx;
            margin-bottom: 16rpx;
            font-size: 70rpx;
            color: #42ae3c;
            text-align: center;
          }

          &:nth-child(2) {
            .share-icon {
              color: #ff5f33;
            }
          }
        }
      }
    }

    /* 显示或关闭内容时动画 */

    .open {
      transform: translateY(0);
      transition: all 0.3s ease-out;
    }

    .close {
      transform: translateY(310rpx);
      transition: all 0.3s ease-out;
    }
  }

  .model-empty {
    width: 500rpx;
    height: 480rpx;
  }

  &-title {
    width: 100%;
    padding: 20rpx;
    box-sizing: border-box;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }

  &-subtitle {
    font-size: 24rpx;
    color: #d82821;
    text-align: right;
    margin-bottom: 20rpx;
  }

  &-log {
    width: 100%;
    height: 348rpx;
    margin: 20rpx 0;

    > image {
      width: 100%;
      height: 348rpx;
    }
  }

  &-introduction {
    background: #ffffff;
    box-shadow: 0rpx 5rpx 0rpx 1rpx rgba(216, 40, 33, 0.3);
    border: 1rpx solid #cb313f;
    padding: 18rpx 0;
    margin-bottom: 52rpx;

    > image {
      width: 70rpx;
    }

    &-content {
      padding: 20rpx;
      box-sizing: border-box;
    }

    .introduction-content {
      font-size: 24rpx;
      color: #d82821;
      line-height: 40rpx;
      padding: 20rpx;
      box-sizing: 20rpx;
    }
  }
  .person-message {
    width: 100%;
    text-align: center;
    font-size: 24rpx;
    color: #d82821;
    margin-top: 20rpx;
  }

  .show-title {
    .title-icon {
      width: 50rpx;
      height: 50rpx;
      background: url("https://kindoucloud.com:8077/api/mongoFile/previewImage/jwsq/657ea9106affce1e6fd24a33");
      background-size: cover;
    }

    .title {
      font-size: 30rpx;
      font-weight: bold;
      color: #d82821;
      margin-left: 20rpx;
    }
  }

  &-show {
    width: 100%;
    // height: 350rpx;
    padding-bottom: 100rpx;
    margin: 20rpx 0;
    background: #ffffff;
    box-shadow: 0rpx 6rpx 16rpx 1rpx rgba(177, 177, 177, 0.4);
    border-radius: 20rpx;
    position: relative;

    .video-container {
      width: 100%;

      > video {
        width: 100%;
        // height: auto;
      }
    }

    .audio-footer {
      position: absolute;
      bottom: 20rpx;
      width: 100%;
      text-align: center;
      color: #d82821;
      font-size: 28rpx;
    }

    .video {
      padding: 20rpx;
      box-sizing: border-box;
      // box-shadow: 0rpx 6rpx 16rpx 1rpx rgba(177, 177, 177, 0.3);
      border-radius: 10rpx;

      &-image {
        flex-shrink: 0;
        margin-right: 30rpx;
      }

      &-right {
        width: 100%;
        font-size: 22rpx;
        color: #919191;

        .right-title {
          font-size: 28rpx;
          overflow: hidden;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
          margin-right: 20rpx;
        }
      }
    }
  }

  &-content {
    margin: 40rpx 0;
    font-size: 28rpx;
    color: #333;
  }
}
</style>
